package com.jiazhong.basic.pack0309.shousi;

import com.jiazhong.basic.pack0309.shousi.ListDemo;

import java.util.Arrays;

public class ArrayListDemo<E> implements ListDemo<E> {
    private static final int DEFAULT_RONGLIANG = 10;
    private static final Object[] EMPTY_ELEMENT = {};
    private Object[] elementData;
    private int size;

    public ArrayListDemo() {
        this.elementData = EMPTY_ELEMENT;
    }

    @Override
    public void add(Object o) {
        // 判断容器是否满了
        if (size == elementData.length) {
            // 满了 扩容
            grow(size);
        }
        this.elementData[size] = o;
        size = size + 1;
    }

    @Override
    public void add(int index, E e) {
        // 判断容器是否满了
        if (size == elementData.length) {
            // 满了 扩容
            grow(size);
        }
        if (index < 0 || index > size - 1) {
            throw new IndexOutOfBoundsException("越界了");
        }
        Object[] elementData = this.elementData;
        System.arraycopy(elementData, index, elementData, index + 1, size - index);
        elementData[index] = e;
        this.elementData = elementData;
        this.size = this.size + 1;
    }

    @Override
    public void remove(int index) {
        if (index < 0 || index > size - 1) {
            throw new IndexOutOfBoundsException("越界了");
        }
        final Object[] elementData = this.elementData;
        System.arraycopy(elementData, index + 1, elementData, index, size - index);
        elementData[size - 1] = null;
        this.size = this.size - 1;
        this.elementData = elementData;
    }

    @Override
    public E get(int index) {
        if (index < 0 || index > size - 1) {
            throw new IndexOutOfBoundsException("越界了");
        }
        return (E) this.elementData[index];
    }

    @Override
    public int indexOf(E e) {
        for (int i = 0; i < size; i++) {
            Object o = this.elementData[i];
            if(o.equals(e)){
                return i;
            }
        }
        return -1;
    }

    private void grow(int size) {
        if (size == 0) {
            this.elementData = new Object[DEFAULT_RONGLIANG];
            return;
        }
        System.out.println("扩容后的效果是：");
        int o = this.elementData.length;
        int n = o + (o >> 1);
        System.out.println(n);
        Object[] newElementData = Arrays.copyOf(this.elementData, n);
        this.elementData = newElementData;
        System.out.println("新数组是：" + Arrays.toString(this.elementData));
    }

    @Override
    public String toString() {
        String str = "[";
        for (int i = 0; i < size; i++) {
            str += this.elementData[i] + ",";
        }
        str += "]";
        return str;
    }
}
